#!/usr/bin/python3
# -*- coding: utf-8 -*-
# ======================================#
# @Author   : duanqizhong
# @time     : 2020/6/8 0:10
# @file     : auth.py
# @Software : PyCharm
# ======================================#

from flask import Blueprint, jsonify, session, request
from flask import make_response
from werkzeug.security import check_password_hash

from apps.config import DOMAIN_SUFFIX
from apps.models.dboperator import query_table_data, update_table_data
from apps.models.logger import log
from apps.models.table_crud import query_table

auth_bp = Blueprint("auth", __name__, url_prefix="/api/v1")


@auth_bp.route("/login", methods=(["POST"]))
def login():
    try:
        args = request.get_json()
        username = args.get("email")
        email = f"{username}@{DOMAIN_SUFFIX}"
        input_password = args.get("password")
        res = query_table("user", {"email": email}, fetchone=True)
        if res.get("status"):
            data = res.get("data")
            if data:
                password = data.get("password")
                if check_password_hash(password, input_password):
                    # 登陆成功
                    role = str(data.get("role"))
                    session["username"] = email
                    session["role"] = role
                    session.permanent = True
                    response = make_response(jsonify(res))
                    response.set_cookie("SessionId", email)
                    response.set_cookie("role", role)
                    return response
                else:
                    res["status"] = False
                    res["data"] = None
                    res["msg"] = f"password was wrong!"
                    log.warning(f"{username} password was wrong!")
            else:
                res["status"] = False
                res["msg"] = f"account {email} not exists!"
                log.warning(f"account {email} not exists!")
            return jsonify(res)
        else:
            return jsonify(res)
    except Exception as e:
        log.error(str(e))


@auth_bp.route("/logout")
def logout():
    infos = {
        "status": True,
        "msg": "Logout sucessed!"
    }

    if "username" in session:
        del session["username"]

    return jsonify(infos)


@auth_bp.route("/initPwd",methods=(["PUT"]))
def init_pwd():
    infos = {
        "status": True,
        "msg": "Init password sucessed!"
    }
    try:
        args = request.get_json()
        table = args["table"]
        email = args["email"]
        where = {
            "email": email
        }
        user_info = query_table_data(table, where, True)
        if user_info.get("status"):
            data = user_info.get("data")
            value_dict = {
                "id": data.get("id"),
                "password": "abc123"
            }
            infos = update_table_data(table, value_dict)
        else:
            infos = user_info
    except Exception as e:
        infos["status"] = False
        infos["msg"] = str(e)

    return jsonify(infos)


@auth_bp.route("/modifyPwd",methods=(["PUT"]))
def modify_pwd():
    infos = {
        "status": True,
        "msg": "Modify password sucessed!"
    }
    try:
        args = request.get_json()
        table = args["table"]
        email = args["email"]
        old_pwd = args["oldPwd"]
        new_pwd = args["newPwd"]
        sure_pwd = args["surePwd"]
        if new_pwd!=sure_pwd:
            infos["status"] = False
            infos["msg"] = "Two input password must be consistent!"
            return jsonify(infos)
        where = {
            "email": email,
            # "id": args["id"]
        }
        user_info = query_table_data(table, where, True)
        if user_info.get("status"):
            data = user_info.get("data")
            if check_password_hash(data.get("password"),old_pwd):
                value_dict = {
                    "id": data.get("id"),
                    "password": new_pwd
                }
                infos = update_table_data(table, value_dict)
            else:
                infos["status"] = False
                infos["msg"] = "input password was wrong!"
        else:
            infos = user_info
    except Exception as e:
        infos["status"] = False
        infos["msg"] = str(e)
    return jsonify(infos)
